package demo3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-08-08
 * Time: 19:52
 */
public class TcpEchoclient {
    
    private Socket socket = null;
    
    public TcpEchoclient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);

//        while (true){
//            try (InputStream inputStream = socket.getInputStream();
//                 OutputStream outputStream = socket.getOutputStream()){
//                System.out.print("-> ");
//                String request = scanner.next();
//                PrintWriter printWriter = new PrintWriter(outputStream);
//                printWriter.println(request);
//                printWriter.flush();
//                Scanner scanner1 = new Scanner(inputStream);
//                String response = scanner1.next();
//                System.out.println(response);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while (true){
                System.out.print("-> ");
                String request = scanner.next();
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();
                Scanner scanner1 = new Scanner(inputStream);
                String response = scanner1.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoclient tcpEchoclient = new TcpEchoclient("127.0.0.1", 9090);
        tcpEchoclient.start();
    }

}

